import React from "react"
import { MenuItem, MenuType } from "@/types/layout"
import { RouteObject } from "react-router-dom"
import LazyLoad from "./LazyLoad"
export interface IFlatMenuType {
    key: string
    path: string
    name: string,
    menuType:MenuType
}
interface IMenuItem {
    key: string
    label: string
    icon: React.ReactNode
    children?: IMenuItem[]
}
/**
 * 扁平化菜单
 * @param menu 菜单列表
 * @returns 扁平化菜单
 */
export function flattenTreeByMenu(menu: MenuItem[]): IFlatMenuType[] {
    let flatArray: IFlatMenuType[] = []
    menu.forEach((node) => {
        const { id, path, menuName, children,menuType } = node
        flatArray.push({ key: id.toString(), path, name: menuName,menuType })
        if (children) {
            flatArray = flatArray.concat(flattenTreeByMenu(children))
        }
    })
    return flatArray
}

/**
 * 添加路由配置
 * @param menu 菜单列表
 * @returns 动态路由表
 */
export function addRouteToMenu(menu: MenuItem[]): RouteObject[] {
    let temp: RouteObject[] = []
    menu.forEach((m) => {
        if (m.menuType === 'C') {
            const obj = {
                path: m.path,
                element: LazyLoad(m.component)
            }
            temp.push(obj)
        } 
         if (m.children && m.children.length) {
            temp = temp.concat(addRouteToMenu(m.children))

        }
    })

    return temp
}
/**
* 菜单列表添加icon
* @param menu 菜单列表
*/
export function addIconToMenu(menu: MenuItem[]): IMenuItem[] {
    const temp: IMenuItem[] = []
    menu.filter(el => el.visible === '0').forEach((item) => {
        const { id, menuName, icon } = item
        const newItem: IMenuItem = {
            label: menuName,
            key: id.toString(),
            icon: icon ? React.createElement('span', { className: `iconfont ${item.icon}`, style: { color: '#1677ff' } }) : ''
        }
        const children = item.children?.filter(el => el.visible === '0')
        if (children && children.length) {
            newItem.children = addIconToMenu(children)
        }
        temp.push(newItem)
    })

    return temp
}

export function findNodeIdsByPath(menu: MenuItem[], path: string): string[] {
    const result: string[] = []
    function dfs(node: MenuItem) {
        if (path.startsWith(node.path)) {
            result.push(node.id.toString())
        }

        if (node.children) {
            node.children.forEach((child) => {
                dfs(child)
            })
        }
    }

    menu.forEach((node) => {
        dfs(node)
    })

    return result
}
